package arithmetic;

import org.junit.jupiter.api.Test;

/**
 * 删除有序数组的重复项
 *
 * @author gaojie
 * @date 2022-02-25
 */
public class RemoveDuplicates {

    @Test
    void test() {
        assert fun(new int[]{1, 1, 2}) == 2;
        assert fun(new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}) == 5;
    }

    /**
     * 1.若长度小于2，则直接返回
     * 2.用一个值记录上次出现的值，遍历数组
     * 3.当发现不一致时，按照下标替换到指定位置
     */
    int fun(int[] nums) {

        // 若长度小于2，则直接返回
        int length = nums.length;
        if (length < 2) return length;

        int temp = nums[0], index = 1;
        System.out.print(temp + "-");
        for (int i = 1; i < length; i++) {
            int cur = nums[i];

            // 若值发生变化，则按照顺序往前搬
            if (cur != temp) {
                nums[index++] = cur;
                temp = cur;
                System.out.print(cur + "-");
            }
        }

        System.out.printf("index: %d%n", index);
        return index;
    }
}
